<template lang="pug">
div
  table.table
    thead
      tr
        td 模块
        td(:width=300) 显示名称
        td(:width=50) 排序
        td.text-center 启用
        td.text-center 操作
    tbody
      template(v-for='menu in flatMenu')
        tr
          td
            span(v-if='menu.depth > 0') |{{ '--'.repeat(menu.depth) }} {{ "\u0020" }}
            span {{ menu.name }}
          td
            //- {{ menu.displayName }}
            span(v-if='menu.module === "external"') {{ menu.id }}
            Input(v-model='menu.displayName', size='small', v-else)
          td
            Input(v-model='menu.weight', size='small', :number='true', @on-change='checkNumber')
          td.text-center
            i-switch(size='small', v-model='menu.enabled')
          td.text-center
            div(v-if='menu.editable')
              a(@click.stop='edit(menu)') 编辑
              | &nbsp; &nbsp;
              a 删除
        //- tr(v-for='submenu in menu.children')
          td |-- {{ submenu.name }}
          td
            //- {{ submenu.displayName }}
            span(v-if='submenu.module === "external"') {{ submenu.id }}
            Input(v-model='submenu.displayName', size='small', v-else)
          td
            Input(v-model='submenu.weight', size='small', :number='true', @on-change='checkNumber')
          td.text-center
            i-switch(size='small', v-model='submenu.enabled')
          td.text-center
            div(v-if='submenu.editable')
              a(@click.stop='edit(submenu)') 编辑
              | &nbsp; &nbsp;
              a(@click.stop='remove(submenu)') 删除

  div(style='margin-top: 20px')
    Button(type='primary', @click='modal.add = true') 添加
    Button(type='success', :loading='updating', @click='update') 保存

  Modal(
    v-model='modal.add',
    :loading='true'
    @on-ok='addMenu'
    @on-cancel='modal.add = false')

    Form(v-model='formData', :label-width=60)
      FormItem(label='类型')
        Select(v-model='formData.module')
          Option(value='external') 外链
          Option(value='page') 站内页面（页面管理模块）
      template(v-if='formData.module === "external"')
        FormItem(label='名称')
          Input(v-model='formData.name')
      FormItem(:label='formData.module === "external" ? "链接地址" :  "页面ID"')
        Input(v-model='formData.id')
      FormItem(label='所属')
        Select(v-model='formData.pid', clearable)
          Option(:value='0') - 无 -
          Option(v-for='item in menus', :value='item.id', :key='item.id') {{ item.name }}

  Modal(
    v-model='modal.edit',
    @on-ok='beforeMenuSave',
    @on-cancel='modal.edit = false')

    Form(v-model='menuEditing', :label-width=60)
      FormItem(label='名称')
        Input(v-model='menuEditing.name')
      FormItem(:label='menuEditing.module === "external" ? "链接地址" :  "页面ID"')
        Input(v-model='menuEditing.id')
      FormItem(label='所属')
        Select(v-model='menuEditing.pid', clearable)
          Option(:value='0') - 无 -
          Option(v-for='item in menus', v-if='item.id !== menuEditing.id', :value='item.id', :key='item.id') {{ item.name }}
</template>

<script>
import { mapState } from 'vuex'
import uuidv1 from 'uuid/v1'
import menuApi from '@/apis/menu'
import pageApi from '@/apis/page'
import store from '@/store'
import Util from '@/libs/util'
import { sortBy } from 'lodash'

export default {
  beforeRouteEnter (to, from, next) {
    menuApi.getMenu(store.state.app.id)
      .then(data => {
        next(vm => (vm.menus = data))
      })
  },
  data () {
    return {
      modal: {
        add: false,
        edit: false
      },
      menus: [],
      updating: false,
      formData: {
        name: '',
        module: '',
        id: '',
        pid: ''
      },
      menuEditing: {}
    }
  },
  computed: {
    flatMenu () {
      // flat menu is a reference to menus, as it's not a deep clone of menus.
      return Util.flattenTree(this.menus, [], 0, function (items) {
        return sortBy(items, ['weight']).map((item, weight) => ({ ...item, weight }))
      })
    },
    ...mapState({
      app: state => state.app.info
    })
  },
  mounted () {
    menuApi.getMenu(this.app.id)
      .then(data => {
        this.menus = data
      })
  },
  methods: {
    update () {
      this.updating = true
      menuApi.patchMenu({
        gid: this.app.id,
        data: this.menus
      }).then(() => {
        this.updating = false
        this.$Message.success('更新成功')
      })
    },
    checkNumber (e) {
      // alert(val)
      console.log(typeof e.target.value)
      if (parseInt(e.target.value) < 0) {
        alert('请输入数字')
        e.focus()
      }
    },
    edit (menu) {
      this.menuEditing = menu
      this.modal.edit = true
    },
    remove (menu) {
      if (menu.pid) {
        let idx = this.menus.findIndex(item => (menu.pid === item.id))
        // console.log(parentMenuItem)
        console.log(idx, this.menus[idx])
        // delete parentMenuItem.children[menu.id]
        delete this.menus[idx].children[menu.uuid]
      }
      // console.log(this.menus[menu.pid])
      this.$forceUpdate()
    },
    beforeMenuSave () {
      this.menuEditing.displayName = this.menuEditing.name
    },
    async addMenu () {
      try {
        const uuid = uuidv1()
        let { id, pid, name, module } = this.formData
        if (module === 'page') {
          const page = await pageApi.getPageDetail(id)
          name = page.title
        }
        const newMenuItem = {
          name,
          displayName: name,
          module,
          uuid,
          id,
          pid,
          weight: 100,
          editable: true
        }

        if (pid) {
          let menu = this.menus.find(item => (item.id == pid))  // eslint-disable-line
          menu.children = Object.prototype.toString.call(menu.children) === '[object Object]' ? menu.children : {}
          menu.children[uuid] = newMenuItem
        } else {
          this.menus.push(newMenuItem)
        }
      } catch (e) {
        this.$Message.error('页面不存在')
      }

      this.modal.add = false
      // this.$forceUpdate()
    }
  }
}
</script>
